import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import './shared/models/map_location.model.dart';
import './shared/services/map_location_service.service.dart';
import './shared/services/map_service.service.dart';
import './shared/services/navigator_helper.service.dart';
import './shared/widgets/map_location_selector.widget.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // For locating user position.
  late final MapLocationService _mapLocationService =
      MapLocationService(_onLcationChanged);

  // For retrieving geo formatted address with coordinate.
  final MapService _mapService = MapService();

  MapLocation _location = MapLocation();

  @override
  void initState() {
    super.initState();

    _checkOnAppPermission().then((_) async {
      await _mapLocationService.startLocation();
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: const Text('高德地图'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: Text(_location.formattedAddress ?? "正在定位 ..."),
            onTap: _gotoMapLocationSelector,
          ),
        ],
      ),
    );
  }

  /// Listens on location change event and updates location info.
  void _onLcationChanged(double? latitude, double? longitude) async {
    if (latitude != null && longitude != null) {
      // Gets geo formatted address with coordinate.
      final res = await _mapService.queryByCoordinate(latitude, longitude);

      if (mounted) {
        setState(() => _location = res!);
      }
    }
  }

  /// Goes to map location selector.
  Future<void> _gotoMapLocationSelector() async {
    final location = await NavigatorHelper.push<MapLocation>(
      context,
      MapLocationSelector(_location),
    );

    if (location != null) {
      if (mounted) {
        setState(() {
          _location = location;
        });
      }
    }
  }

  Future<void> _checkOnAppPermission() async {
    if (await Permission.locationWhenInUse.status != PermissionStatus.granted) {
      await Permission.locationWhenInUse.request();
    }
  }
}
